<?php

namespace app\api\service;

use api\Xiaoju;
use app\model\OilStore;
use app\model\OilStoreItem;
use app\model\PlatformToken;

class OilXiaojuService extends CommonService
{
    public $uniqId = '';
    public $appPlatform = '1';
    public $xiaoju;

    public function __construct(Xiaoju $xiaoju)
    {
        $this->xiaoju = $xiaoju;
    }

    /**
     * 获取小桔的平台密钥.
     * $force 是否强制获取.
     */
    public function queryToken($force = 0)
    {
        $where = [
           ['app_platform', '=', $this->appPlatform],
           ['app_key', '=', $this->xiaoju->config['app_key']],
        ];
        $tokenInfo = PlatformToken::where($where)->find();
        if ($force || !$tokenInfo || ($tokenInfo && $tokenInfo->expire_time <= time())) {
            $info = $this->xiaoju->curl('queryToken', ['appSecret' => $this->xiaoju->config['app_secret']]);
            if (0 != $info['code']) {
                doLog('获取小桔token失败'.json_encode($info, JSON_UNESCAPED_UNICODE));
                // todo 重试
                return $this->inValiReturn('获取小桔token失败');
            } else {
                $updateArr = [
                    'access_token' => $info['data']['accessToken'],
                    'expire_time' => time() + ($info['data']['availableTime'] - 200),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                if (!$tokenInfo) {
                    $updateArr['app_key'] = $this->xiaoju->config['app_key'];
                    $updateArr['app_platform'] = $this->appPlatform;
                    $tokenInfo = new  PlatformToken();
                }

                foreach ($updateArr as $k => $v) {
                    $tokenInfo->{$k} = $v;
                }
                $res = $tokenInfo->save();
                if (!$res) {
                    doLog('获取小桔token，入库失败'.json_encode($info, JSON_UNESCAPED_UNICODE));
                }
            }
        }

        return $this->valiReturn(['access_token' => $tokenInfo->access_token]);
    }

    /**
     * 从小桔方拉取加油站列表.
     */
    public function getStore($supplierId)
    {
        ignore_user_abort(true);
        set_time_limit(0);

        $this->uniqId = uniqid('');

        // 统计已有数量
        $where = [
            ['supplier_id', '=', $supplierId],
            ['batch_id', '=', $this->uniqId],
        ];
        $pageSize = 100;
        $maxLoop = 5000;
        $loopCount = 0;

        // 循环拉取数据
        try {
            while (true) {
                if ($loopCount >= $maxLoop) {
                    doWarning('OilStoreService->getStore,'.__LINE__.',while次数过高跳出循环,uniqId='.$this->uniqId);
                    break;
                }
                ++$loopCount;
                $count = OilStore::where($where)->count();
                $pageIndex = floor($count / $pageSize);
                if (!$pageIndex) {
                    $pageIndex = 0;
                }
                ++$pageIndex;
                $queryData = ['pageIndex' => $pageIndex, 'pageSize' => $pageSize];
                $ret = $this->xiaoju->curl('queryStoreList', $queryData);
                if ($ret['code']) {
                    doWarning('OilStoreService->getStore,'.__LINE__.',接口请求返回code!=0,uniqId='.$this->uniqId);
                    break;
                }

                $ret = $ret['data'];
                $ret['storeInfoList'] = $this->getStoreData($ret['storeInfoList'], $supplierId);
                if ($ret['storeInfoList']) {
                    $oilStore = new OilStore();
                    $res = $oilStore->replace()->saveAll($ret['storeInfoList']['store']);
                    if (!$res) {  // 预警
                        doWarning('OilStoreService->getStore,'.__LINE__.',批量入库失败预警,uniqId='.$this->uniqId);
                        break;
                    }

                    $oilStoreItem = new OilStoreItem();
                    $res = $oilStoreItem->replace()->saveAll($ret['storeInfoList']['item']);
                    if (!$res) {  // 预警
                        doWarning('OilStoreService->getStore,'.__LINE__.',批量入库失败预警,uniqId='.$this->uniqId);
                        break;
                    }
                }

                $ret['totalSize'] = intval($ret['totalSize']);

                $count += count($ret['storeInfoList']);
                if ($count > $ret['totalSize']) {  // 预警
                    doWarning('OilStoreService->getStore,'.__LINE__.',数据库数量高于第三方拉取的数量,uniqId='.$this->uniqId);
                    break;
                } elseif ($count === $ret['totalSize']) {  //  数据获取完成
                    doLog('OilStoreService->getStore,'.__LINE__.',正常数据拉取完成,uniqId='.$this->uniqId);
                    break;
                }
            }

            // step 删除存在库里 但是拉取不到的数据 这类是在第三方已经删除的数据
            $deleteWhere = [
                ['supplier_id', '=', $supplierId],
                ['batch_id', '<>', $this->uniqId],
            ];
            $datetime = date('Y-m-d H:i:s');
            $res = OilStore::where($deleteWhere)->update(['deleted_at' => $datetime]); //$datetime = date('Y-m-d H:i:s');
            $res = OilStoreItem::where($deleteWhere)->update(['deleted_at' => $datetime]); //$datetime = date('Y-m-d H:i:s');
        } catch (\Exception $e) {
            doLog('异常OilStoreService->getStore,'.__LINE__.',uniqId='.$this->uniqId.'，异常信息：'.getExceptionMsg($e));
            doWarning('异常OilStoreService->getStore,'.__LINE__.',uniqId='.$this->uniqId.'，异常信息：'.getExceptionMsg($e));
        }

        return $this->valiReturn([]);
    }

    /*
    * 获取油品价格
    */
    public function queryStorePrice($param)
    {
        foreach ($param as $k => $v) {
            $queryData[camelize($k)] = $v;
        }

        // 处理成store_id为key
        $list = $this->xiaoju->curl('queryStorePrice', $queryData);
        if (!$list['code']) {
            $storePrice = [];
            foreach ($list['data']['itemInfoList'] as $k => $v) {
                $storePrice[$v['storeId']] = $v;
            }

            $list['data'] = $storePrice;
        }

        return  $this->forceReturn($list);
    }

    /* 获取跳转连接 */
    public function queryEnergyUrl($queryData)
    {
        return  $this->forceReturn($this->xiaoju->curl('queryEnergyUrl', $queryData));
    }

    /*
     获取订单详情
     transToTable 是否转化成 订单表格式数据 1 是
    */
    public function queryOrderInfo($orderId, $transToTable = 1)
    {
        $list = $this->xiaoju->curl('queryStorePrice', ['orderId' => $orderId]);
        if ($list['code']) {
            return  $this->forceReturn($list);
        }
        if ($transToTable) {
            $list['data'] = $this->getOrderData($list['data']);
        }

        return  $this->forceReturn($list);
    }

    /*
    主动拉取订单
    */
    public function queryOrderList($pageIndex, $pageSize, $queryStartTime, $queryEndTime)
    {
        $list = $this->xiaoju->curl('queryOrderList', ['pageIndex' => $pageIndex, 'pageSize' => $pageSize, 'queryStartTime' => $queryStartTime, 'queryEndTime' => $queryEndTime]);

        return  $this->forceReturn($list);
    }

    /*  store列表数据转成数据库字段 */
    public function getStoreData($data, $supplierId)
    {
        $result = ['item' => [], 'store' => []];
        if (!$data) {
            return $result;
        }

        foreach ($data as $k => $v) {
            foreach ($v as $k2 => $v2) {
                $tempV[uncamelize($k2)] = $v2; // 下一级数组保存成json 且不转成下划线格式
            }
            $tempV['supplier_id'] = $supplierId;
            $tempV['batch_id'] = $this->uniqId;
            //$tempV['created_at'] = $datetime;
            //$tempV['updated_at'] = $datetime;
            //$tempV['step'] = 0;
            // 处理

            // item 数据处理
            if ($tempV['item_info_list']) {
                foreach ($tempV['item_info_list'] as $k2 => $v2) {
                    foreach ($v2 as $k3 => $v3) {
                        $v2[uncamelize($k3)] = $v3; // 下一级数组保存成json 且不转成下划线格式
                        unset($v2[$k3]);
                    }
                    $v2['supplier_id'] = $supplierId;
                    $v2['batch_id'] = $this->uniqId;
                    $result['item'][] = $v2;
                }
            }
            foreach ($tempV as $k2 => $v2) {
                $keysArr = [
                    'supplier_id',
                    'store_id',
                    'store_name',
                    'store_logo',
                    'city_name',
                    'province_name',
                    'address',
                    'lon',
                    'lat',
                    'brand_name',
                    'hui_labels',
                    'business_hours_start',
                    'business_hours_end',
                    'batch_id',
                ];

                if (!in_array($k2, $keysArr)) {
                    unset($tempV[$k2]);
                }

                $tempV['brand_name'] = $tempV['brand_name'] ?? '';  // 返回值没有 brand_name 情况
            }

            $result['store'][] = $tempV;
        }

        return  $result;
    }

    /*
     不处理 代理商 供应商 和用户信息
    */
    public function getOrderData($data)
    {
        $data['status'] = $data['payStatus'];
        if (isset($data['refundTime'])) {
            $data['refund_at'] = $data['refundTime'];
        }
        unset($data['payStatus'],$data['refundTime']);
        $orderData = batchUncamelize($data);
        //step  其他参数完善
        //$orderData['user_id'] = $userInfo->user_id;
        //$orderData['cnid'] = $userInfo->app_id;
        //$orderData['agent_id'] = 查数据库;
        //$orderData['supplier_id'] = $supplierInfo->id;
        $orderData['out_order_id'] = $orderData['order_id'];
        unset($orderData['order_id']);
        $orderData['total_amount'] = $orderData['total_money'];
        unset($orderData['total_money']);
        $orderData['pay_amount'] = $orderData['real_money'];
        unset($orderData['real_money']);

        return $orderData;
    }
}
